package com.zhan.signalling.data.listener;

import com.alibaba.fastjson.JSONObject;
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.listener.DataListener;
import com.zhan.signalling.check.AccoutPermissionCheck;
import com.zhan.signalling.commons.Constants;
import com.zhan.signalling.commons.SocketEvent;
import com.zhan.signalling.entity.WhiteBoardRecord;
import com.zhan.signalling.message.AccoutType;
import com.zhan.signalling.message.Message;
import com.zhan.signalling.message.Result;
import com.zhan.signalling.store.StoreMessageFactory;
import com.zhan.signalling.store.StoreMessageStore;
import com.zhan.signalling.util.RedisUtil;

/**
 * 白板事件
 * @author knight
 *
 */
public class WhiteBoardListener implements DataListener<Message> {
	
	private StoreMessageStore dataHandler;
	
	public WhiteBoardListener() {
		dataHandler = StoreMessageFactory.getHandler();
		dataHandler.initStore(WhiteBoardRecord.class);
	}
	
	public void onData(SocketIOClient client, Message data, AckRequest ackSender) throws Exception {
		
		// 校验权限
		AccoutPermissionCheck.check(client, SocketEvent.WHITEBOARD_EVENT);
		
		JSONObject user = client.get(Constants.USER_KEY);
		Integer userRole = client.get(Constants.USER_TYPE);
		String groupId = client.get(Constants.GROUP_KEY);
		String platform = client.getNamespace().getName();
		
		WhiteBoardRecord record = new WhiteBoardRecord();
		record.setUuId(client.getSessionId().toString());
		record.setContent(data.getContent().toString());
		record.setEventType(SocketEvent.WHITEBOARD_EVENT);
		record.setExtras(JSONObject.toJSONString(user));
		record.setGroupId(groupId);
		record.setSendTime(data.getSendTime());
		record.setCreateTime(System.currentTimeMillis());
		record.setPlatform(platform);
		record.setRole(AccoutType.getInstance(userRole).name());
		
		// 保存消息
		Long seqId = dataHandler.saveWhiteBoard(record);
		// 存redis
		RedisUtil.addLastSeqId(record.getPlatform_groupId() + ":" + SocketEvent.CHAT_EVENT, seqId);
		client.getNamespace().getRoomOperations(groupId)
				.sendEvent(SocketEvent.WHITEBOARD_EVENT, 
						new Result(record, Constants.SUCCESS));
		
	}

}
